package com.jiamao.goplay.app;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.jiamao.goplay.R;
import com.jiamao.goplay.base.LibContainerActivity;
import com.jiamao.goplay.immsg.CommdAttachment;
import com.jiamao.goplay.immsg.MatchAttachment;
import com.jiamao.goplay.immsg.CustomAttachParser;
import com.jiamao.goplay.immsg.MatchRemoveAttachment;
import com.jiamao.goplay.immsg.MsgViewHolderCommd;
import com.jiamao.goplay.immsg.MsgViewHolderCrops;
import com.jiamao.goplay.immsg.MsgViewHolderMatchRemove;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.ui.login.LoginWeChatFragment;
import com.jiamao.goplay.ui.main.MainActivity;
import com.jiamao.goplay.ui.welcome.WelComeActivity;
import com.jiamao.goplay.view.EmptyCallback;
import com.jiamao.goplay.view.FindEmptyCallback;
import com.jiamao.goplay.view.LoadingCallback;
import com.jiamao.goplay.view.LocationErrorCallback;
import com.jiamao.goplay.view.TimeoutCallback;
import com.jiamao.lib.BaseLibApplication;
import com.kingja.loadsir.core.LoadSir;
import com.kongzue.dialog.util.DialogSettings;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nim.uikit.api.model.location.LocationProvider;
import com.netease.nim.uikit.api.model.session.SessionCustomization;
import com.netease.nim.uikit.business.session.actions.BaseAction;
import com.netease.nim.uikit.business.session.actions.ImageAction;
import com.netease.nim.uikit.business.session.actions.VideoAction;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.SystemMessage;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.tamsiree.rxkit.BuildConfig;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.crash.TCrashProfile;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.ArrayList;


import cn.jpush.android.api.JPushInterface;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.ContainerActivity;
import me.goldze.mvvmhabit.crash.CaocConfig;
import me.goldze.mvvmhabit.crash.CustomActivityOnCrash;
import me.goldze.mvvmhabit.crash.DefaultErrorActivity;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;
import skin.support.SkinCompatManager;
import skin.support.app.SkinAppCompatViewInflater;
import skin.support.app.SkinCardViewInflater;
import skin.support.constraint.app.SkinConstraintViewInflater;
import skin.support.design.app.SkinMaterialViewInflater;

/**
 * Created by goldze on 2017/7/16.
 */

public class AppApplication extends BaseLibApplication {
    private static AppApplication sInstance;
    private boolean  isDebug;
    public double lat,lot;
    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        //是否开启打印日志
        isDebug = isApkDebugable(this);

        //是否开启日志打印
        KLog.init(isDebug);
        KLog.d("html"," BuildConfig.DEBUGm " +isDebug);
        //初始化全局异常崩溃
        initCrash();
        initLoadSir();
        initRxTool();
        initRefresh();
        initAliOss();
        initSkin();
        initIMSDK();
        JPushInterface.setDebugMode(true);
       // cn.jpush.android.service.AlarmReceiver
        JPushInterface.init(this);
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });


        DialogSettings.style =DialogSettings.STYLE.STYLE_IOS;
        DialogSettings.theme = DialogSettings.THEME.DARK;
//
//        //内存泄漏检测
//        if (!LeakCanary.isInAnalyzerProcess(this) && isDebug) {
//            LeakCanary.install(this);
//        }

        UMConfigure.preInit(this,  Config.UmengKey, "Umeng");
        PlatformConfig.setWeixin("wx7aafbfc732fce349", "4c4885c574542d785c5757565f8dcfb9");  //appId:wx7aafbfc732fce349    secret:4c4885c574542d785c5757565f8dcfb9
       // UMConfigure.init(this,  "5f9fb03e1c520d30739e1243", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);
        // 选用LEGACY_AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_AUTO);

//        UMShareAPI.getPlatformInfo(MainActivity.this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
//            @Override
//            public void onStart(SHARE_MEDIA share_media) {
//
//            }
//
//            @Override
//            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//
//            }
//
//            @Override
//            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
//
//            }
//
//            @Override
//            public void onCancel(SHARE_MEDIA share_media, int i) {
//
//            }
//        });

        lat=  SPUtils.getInstance().getFloat("lat");
        lot=  SPUtils.getInstance().getFloat("lot");
        //latLng = new LatLng(lat,lot);

    }
    public void initSkin(){
        SkinCompatManager.withoutActivity(this)
                .addInflater(new SkinAppCompatViewInflater())           // 基础控件换肤初始化
                .addInflater(new SkinMaterialViewInflater())            // material design 控件换肤初始化[可选]
                .addInflater(new SkinConstraintViewInflater())          // ConstraintLayout 控件换肤初始化[可选]
                .addInflater(new SkinCardViewInflater())                // CardView v7 控件换肤初始化[可选]
                .setSkinStatusBarColorEnable(false)                     // 关闭状态栏换肤，默认打开[可选]
                .setSkinWindowBackgroundEnable(false)                   // 关闭windowBackground换肤，默认打开[可选]
                .loadSkin();
    }
    public void initIMSDK(){
        DemoCache.setContext(this);
        SDKOptions sdkOptions = NimSDKOptionConfig.getSDKOptions(this);


        NIMClient.init(this, getLoginInfo(), sdkOptions);

        if (NIMUtil.isMainProcess(this)) {
            // 在主进程中初始化UI组件，判断所属进程方法请参见demo源码。
            initUiKit();
            NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new CustomAttachParser());
            NimUIKit.registerMsgItemViewHolder(MatchAttachment.class, MsgViewHolderCrops.class);
            NimUIKit.registerMsgItemViewHolder(MatchRemoveAttachment.class, MsgViewHolderMatchRemove.class);
            NimUIKit.registerMsgItemViewHolder(CommdAttachment.class, MsgViewHolderCommd.class);

//            SPUtils.getInstance().put(Config.APP_SETINGS_TZ,isOpened);
            NIMClient.toggleNotification(SPUtils.getInstance().getBoolean(Config.APP_SETINGS_TZ,true));

        }
    }
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给 SDK 完成，需要添加以下配置。否则无需设置。
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = MainActivity.class; // 点击通知栏跳转到该Activity
        // 呼吸灯配置
        config.ledARGB = Color.GREEN;
        config.ledOnMs = 1000;
        config.ledOffMs = 1500;
        // 通知铃声的uri字符串
        config.notificationSound = "android.resource://com.netease.nim.demo/raw/msg";
        options.statusBarNotificationConfig = config;
        // 配置保存图片，文件，log 等数据的目录
        // 如果 options 中没有设置这个值，SDK 会使用采用默认路径作为 SDK 的数据目录。
        // 该目录目前包含 log, file, image, audio, video, thumb 这6个目录。
        // 如果第三方 APP 需要缓存清理功能， 清理这个目录下面个子目录的内容即可。

        // 配置是否需要预下载附件缩略图，默认为 true
        options.preloadAttach = true;

        // 配置附件缩略图的尺寸大小。表示向服务器请求缩略图文件的大小
        // 该值一般应根据屏幕尺寸来确定， 默认值为 Screen.width / 2


        return options;
    }

    private void initUiKit() {

//        SessionCustomization sessionCustomization = new SessionCustomization();
//        ArrayList<BaseAction> actions = new ArrayList<>();
//        actions.add(new ImageAction());
//        actions.add(new VideoAction());
//
//        sessionCustomization.actions = actions;
//        NimUIKit.setCommonP2PSessionCustomization(sessionCustomization);
//
        UIKitOptions options = new UIKitOptions();
        options.messageRightBackground = R.drawable.message_item_right_selector;
        options.messageLeftBackground = R.drawable.message_item_left_selector;
        // 初始化
        NimUIKit.init(this,options);

        //options.buildNimUserCache = true;

        com.huawei.hms.support.common.ActivityMgr.INST.init(this);
        //HMSAgent.init(application);
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                new Observer<StatusCode> () {
                    public void onEvent(StatusCode status) {
                        //获取状态的描述
                        Log.d("HTML","StatusCode init StatusCode"+status.wontAutoLogin());
                        if (status.wontAutoLogin()) {
                            AppApplication.getInstance().startLogins();
                            // 被踢出、账号被禁用、密码错误等情况，自动登录失败，需要返回到登录界面进行重新登录操作
                        }
                    }
                }, true);

//        NIMClient.getService(SystemMessageObserver.class)
//                .observeReceiveSystemMsg(new Observer<SystemMessage>() {
//                    @Override
//                    public void onEvent(SystemMessage message) {
//                        // 收到系统通知，可以做相应操作
//                        Log.d("HTML","message "+message.toString());
//                    }
//                }, true);
//
        // 如果有自定义通知是作用于全局的，不依赖某个特定的 Activity，那么这段代码应该在 Application 的 onCreate 中就调用
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(new Observer<CustomNotification>() {
            @Override
            public void onEvent(CustomNotification message) {
                //  message.getPushPayload()
                Log.d("HTML","message CustomNotification "+message.toString());
                // 在这里处理自定义通知。
            }
        }, true);
        // 可选定制项
        // 注册定位信息提供者类（可选）,如果需要发送地理位置消息，必须提供。
        // demo中使用高德地图实现了该提供者，开发者可以根据自身需求，选用高德，百度，google等任意第三方地图和定位SDK。
        NimUIKit.setLocationProvider(new LocationProvider() {
            @Override
            public void requestLocation(Context context, Callback callback) {
                    KLog.d("AAAAAAAAA");
            }

            @Override
            public void openMap(Context context, double longitude, double latitude, String address) {
                KLog.d("BBBBBBBBBBBBBB");
            }
        });

        // 会话窗口的定制: 示例代码可详见demo源码中的SessionHelper类。
        // 1.注册自定义消息附件解析器（可选）
        // 2.注册各种扩展消息类型的显示ViewHolder（可选）
        // 3.设置会话中点击事件响应处理（一般需要）
//        SessionHelper.init();

        // 通讯录列表定制：示例代码可详见demo源码中的ContactHelper类。
        // 1.定制通讯录列表中点击事响应处理（一般需要，UIKit 提供默认实现为点击进入聊天界面)
//        ContactHelper.init();

        // 在线状态定制初始化。
//        NimUIKit.setOnlineStateContentProvider(new DemoOnlineStateContentProvider());
    }

    private LoginInfo getLoginInfo() {


        String account = SPUtils.getInstance().getString(Config.UID)+"";
        String token = SPUtils.getInstance().getString(Config.IMToken);
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            DemoCache.setAccount(account.toLowerCase());
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }


    private void initCrash() {
        CaocConfig.Builder.create()
                .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
                .enabled(false) //是否启动全局异常捕获
                .showErrorDetails(true) //是否显示错误详细信息
                .showRestartButton(true) //是否显示重启按钮
                .trackActivities(true) //是否跟踪Activity
                .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
                .errorDrawable(R.mipmap.ic_launcher) //错误图标
                .restartActivity(WelComeActivity.class) //重新启动后的activity
                .errorActivity(DefaultErrorActivity.class) //崩溃后的错误activity
                .eventListener(new CustomEventListener()) //崩溃后的错误监听˙
                .apply();
    }
    /**
     * 监听程序崩溃/重启
     */
    private static   class CustomEventListener implements CustomActivityOnCrash.EventListener {
        //程序崩溃回调
        @Override
        public void onLaunchErrorActivity() {
            Log.e("TAG", "onLaunchErrorActivity()");
        }

        //重启程序时回调
        @Override
        public void onRestartAppFromErrorActivity() {
            Log.e("TAG", "onRestartAppFromErrorActivity()");
        }

        //在崩溃提示页面关闭程序时回调
        @Override
        public void onCloseAppFromErrorActivity() {
            Log.e("TAG", "onCloseAppFromErrorActivity()");
        }

    }

    public void initLoadSir(){

        LoadSir.beginBuilder()
             .addCallback(new LoadingCallback())
              .addCallback(new TimeoutCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new FindEmptyCallback())
                .addCallback(new LocationErrorCallback())
               .setDefaultCallback(LoadingCallback.class)
                .commit();
    }

    public void initRefresh(){
        //设置全局的Header构建器

        //设置 Header 为 贝塞尔雷达 样式
//设置 Footer 为 球脉冲 样式


        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                MaterialHeader materialHeader = new MaterialHeader(context);
               // materialHeader.setProgressBackgroundColorSchemeResource(R.color.black);
                materialHeader.setColorSchemeResources(android.R.color.black);
                return materialHeader;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
               // RefreshFooter
                MaterialHeader materialHeader = new MaterialHeader(context);
                // materialHeader.setProgressBackgroundColorSchemeResource(R.color.black);
                materialHeader.setColorSchemeResources(android.R.color.black);
                return  new BallPulseFooter(context);
                //  return new ClassicsFooter(context);
            }
        });
    }
    public void initRxTool(){
        RxTool.init(this)
                .debugLog(BuildConfig.DEBUG)
                .debugLogFile(false)
                .crashLogFile(true)
                .crashProfile()//以下为崩溃配置
                .backgroundMode(TCrashProfile.BACKGROUND_MODE_CRASH) //default: TCrashProfile.BACKGROUND_MODE_SHOW_CUSTOM
                .enabled(isDebug) //default: true
                .showErrorDetails(true) //default: true
                .showRestartButton(true) //default: true
                .logErrorOnRestart(true) //default: true
                .trackActivities(true) //default: false
                .minTimeBetweenCrashesMs(2000) //default: 3000
                .errorDrawable(R.drawable.crash_logo) //default: bug image
                .apply();
    }

    public void initAliOss(){


// 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。
       // AliOSSUpload.getInstance().init(this);
    }
    public static AppApplication getInstance() {
        if (sInstance == null) {
            throw new NullPointerException("please inherit BaseApplication or call setApplication.");
        }
        return sInstance;
    }

    public void logout(){
        SPUtils.getInstance().put(Config.TOKEN,"");
        SPUtils.getInstance().put(Config.IS_LOGIN,false);
        SPUtils.getInstance().put(Config.UID,"");
        SPUtils.getInstance().put("pz",-1);
        NIMClient.getService(AuthService.class).logout();
    }

    public void startLogins(){
        logout();
        AppManager.getAppManager().finishAllActivity();
        Intent intent = new Intent(this, LibContainerActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ContainerActivity.FRAGMENT, LoginWeChatFragment.class.getCanonicalName());
        startActivity(intent);
    }
}
